<template>
  <div>
    <el-drawer title="商品详情" :visible.sync="visible" size="50%" @close="handleClose">
      <div style="margin: 15px">
        <!--条件搜索表单-->
        <el-row :gutter="20">
          <el-form :inline="true"> </el-form>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-button type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
        </el-row>

        <el-table
          v-loading="loading"
          element-loading-text="正在努力加载数据中..."
          :data="page.list"
          :border="false"
          stripe
          style="width: 100%; margin: 15px 0px"
        >
          <el-table-column type="index" fixed="left" width="80" label="序号" />
          <el-table-column prop="imageUrl" fixed="left" label="商品图片" min-width="100" sortable show-overflow-tooltip>
            <template v-slot="scope">
              <el-image
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                style="width: 60px; height: 60px"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="商品描述" min-width="100" sortable show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" min-width="100" sortable show-overflow-tooltip />

          <!-- 操作 -->
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template slot-scope="scope">
              <el-link type="success" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-link>
              <el-divider direction="vertical" />
              <el-link type="danger" icon="el-icon-remove" @click="remove(scope.row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页导航栏 -->
        <div>
          <el-pagination
            :background="true"
            :current-page="pIndex"
            :page-size="pSize"
            :total="page.total"
            :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
            layout="total, sizes, ->, prev, pager, next, jumper"
            @current-change="getAll"
            @size-change="handleSizeChange"
          />
        </div>

        <div style="margin-top: 15px">
          <el-button @click="visible = false">关 闭</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="showEdit" width="40%" @close="close('productDetailForm')">
      <el-form ref="productDetailForm" :model="productDetail" label-width="100px">
        <el-row :gutter="35">
          <el-col>
            <el-form-item label="商品图片">
              <el-upload
                class="image-upload"
                :action="uploadAction"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="productDetail.imageUrl" :src="productDetail.imageUrl" class="image" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品ID" prop="id" :hidden="true">
              <el-input v-model="productDetail.id" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
            <el-form-item label="商品描述" prop="description">
              <el-input
                type="textarea"
                v-model="productDetail.description"
                placeholder="请输入商品描述"
                :autosize="{ minRows: 3 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="save('productDetailForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import productDetailApi from '@/api/productDetail'

export default {
  props: {
    visible: { type: Boolean, required: true, default: false },
    productId: { type: Number, default: undefined }
  },
  data() {
    return {
      loading: false,
      pIndex: 1,
      pSize: 6,
      searchObj: {
        productId: undefined
      },
      page: [],

      dialogTitle: '',
      showEdit: false,
      productDetail: {
        id: undefined,
        imageUrl: '',
        description: ''
      },
      uploadAction: process.env.VUE_APP_BASE_API + '/file/upload'
    }
  },
  watch: {
    productId: {
      handler(val) {
        this.searchObj.productId = val
        this.productDetail.productId = val
        this.getAll()
      },
      immediate: true
    }
  },
  methods: {
    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      productDetailApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      this.getAll()
    },

    // 关闭
    handleClose() {
      this.$emit('update:visible')
    },

    // 打开表单页面
    openEdit(row) {
      this.dialogTitle = '新增商品详情'
      this.showEdit = true
      this.productDetail.imageUrl = ''

      if (row != null) {
        this.dialogTitle = '编辑商品详情'
        productDetailApi.getById(row.id).then((res) => {
          const data = res.data
          Object.assign(this.productDetail, data)
        })
      }
    },

    // 图片上传成功
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.productDetail.imageUrl = res.data
      }
    },

    // 图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG|PNG|JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }

      return isJPG && isLt2M
    },

    // 保存
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const apiCall = this.productDetail.id
            ? productDetailApi.update(this.productDetail)
            : productDetailApi.save(this.productDetail)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.showEdit = false
            this.getAll()
          })
        }
      })
    },

    // 删除商品详情
    remove(id) {
      this.$confirm('此操作将永久删除商品详情, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          productDetailApi.remove(id).then((resp) => {
            this.$message.success('删除成功！')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    }
  }
}
</script>
